package com.dingshi.security;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Application;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Message;
import android.os.Process;
import android.util.Log;

import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.PatrolApi;
import com.dingshi.security.config.Config;
import com.dingshi.security.db.SettingLoader;

public class SecurityApp extends Application {

	private static final String TAG = "SecurityApp";

	public static ArrayList<Activity> allActivity = new ArrayList<Activity>();

	public static Context appContext;


	private LocationManager locationManager;


	private LocationListener llistener;

	private Location mLocation;

	private Timer timer;

	private MessageListener listener;
	
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		appContext = this.getApplicationContext();
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		
		initGpsLocation();
		
		nightShiftTimer();
	}
	
	public void nightShiftTimer() {
		Log.e("Timer", "保安类型 " + SettingLoader.getGuardType(this));
		if(timer!=null) {
			timer.cancel();
			timer = null;
		}
		timer = new Timer();
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				Log.e("Message", "timer is running");
				Message msg = Message.obtain();
				msg.arg1 = 1;
				if(listener!=null) {
					listener.messageCallBack(msg);
				}
			}

			
		}, Config.Night_IntervalTime, Config.Night_IntervalTime);
	}
	
	
	public void initGpsLocation() {
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Log.e(TAG, "initGps location");
			mLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			String provider = locationManager.getBestProvider(getCriteria(), true);
			llistener = new LocationListener() {
				public void onLocationChanged(Location location) {
					Log.e(TAG, "位置变化了啊！");
					if(mLocation==null) {
						mLocation = location;
					}else {
						if(location!=null&&location.getAccuracy()<mLocation.getAccuracy()) {
							mLocation = location;
							Log.e(TAG, "有经度更低的位置信息获取到");
						}
					}
					if(mLocation!=null) {
						reportPatrol();
					}
				}

				public void onStatusChanged(String provider, int status,
						Bundle extras) {
					

				}

				public void onProviderEnabled(String provider) {

				}

				public void onProviderDisabled(String provider) {
				}
			};
			if (provider != null) {
				locationManager.requestLocationUpdates(provider, 60*1000, 0,llistener);
			}

		}

	}
	
	private void reportPatrol() {
		Log.e("Register", "register is running");
		PatrolApi api = new PatrolApi(appContext);
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				JSONObject jsonEntity = apiResult.getJsonEntity();
				if (jsonEntity != null) {
					// {"d":[{"__type":"DiaryReturn:r","c":"aaa","t":"01:59:05"}],"t":1}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							break;
						case 1:// 数组
							

							break;
						case -1:// 错误
							
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
			}
		});
		Location location = getLocation();
		if(location!=null) {
			api.reportPatrol(1, appContext, SettingLoader.getDepartNum(appContext), SettingLoader.getAreaNum(appContext), SettingLoader.getGuardNum(appContext), location.getLongitude()+"", location.getLatitude()+"");
		}
	}
	
	 /**  
     * 返回查询条件  
     * @return  
     */ 
    private Criteria getCriteria()
    {  
    	Criteria criteria=new Criteria();  
        //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细   
        criteria.setAccuracy(Criteria.ACCURACY_FINE);      
        //设置是否要求速度  
        criteria.setSpeedRequired(false);  
        // 设置是否允许运营商收费    
        criteria.setCostAllowed(false);  
        //设置是否需要方位信息  
        criteria.setBearingRequired(false);  
        //设置是否需要海拔信息  
        criteria.setAltitudeRequired(false);  
        // 设置对电源的需求    
        criteria.setPowerRequirement(Criteria.POWER_LOW);  
        /*
          Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_LOW);
         */
        return criteria;  
    }  
	
	public Location getLocation() {
		return mLocation;
	}

	public static SecurityApp getApp(Context context) {
		return (SecurityApp)context.getApplicationContext();
	}
	
	public static boolean isAppOnForeground() {
		ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			// 应用程序位于堆栈的顶层
			if ("com.gozap.chouti".equals(tasksInfo.get(0).topActivity.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	public static boolean isActivityOnForeground(Activity activity) {
		ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			// activity位于堆栈的顶层
			if (activity.getClass().getName().equals(tasksInfo.get(0).topActivity.getClassName())) {
				return true;
			}
		}
		return false;
	}

	public void exitApp() {
		for (Activity activity : allActivity) {
			activity.finish();
		}
		if(timer!=null) {
			timer.cancel();
			timer = null;
		}
		
		allActivity.clear();
		Process.killProcess(Process.myPid());
		System.exit(0);
	}

	public static Context getAppContext() {
		return appContext;
	}

	public void setMessageListener(MessageListener listener) {
		this.listener = listener;
	}
	
	interface MessageListener {
		void messageCallBack(Message msg);
	}
}
